<template>
    <a-card>
        <div :class="advanced ? 'search' : null">
            <a-form layout="horizontal">
                <div :class="advanced ? null: 'fold'">
                    <a-row>
                        <a-col :md="8" :sm="24">
                            <a-form-item
                                    label="用户名"
                                    :labelCol="{span: 5}"
                                    :wrapperCol="{span: 18, offset: 1}"
                            >
                                <a-input placeholder="请输入"/>
                            </a-form-item>
                        </a-col>
                        <a-col :md="8" :sm="24">
                            <a-form-item
                                    label="电子邮箱"
                                    :labelCol="{span: 5}"
                                    :wrapperCol="{span: 18, offset: 1}"
                            >
                                <a-input placeholder="请输入"/>
                            </a-form-item>
                        </a-col>
                    </a-row>
                </div>
                <span style="float: right; margin-top: 3px;">
          <a-button type="primary">查询</a-button>
          <a-button style="margin-left: 8px">重置</a-button>
          <a @click="toggleAdvanced" style="margin-left: 8px">
            {{advanced ? '收起' : '展开'}}
            <a-icon :type="advanced ? 'up' : 'down'"/>
          </a>
        </span>
            </a-form>
        </div>
        <div>
            <a-space class="operator">
                <a-button @click="addUser()" type="primary">新建</a-button>
                <a-button>批量操作</a-button>
                <a-dropdown>
                    <a-menu @click="handleMenuClick" slot="overlay">
                        <a-menu-item key="delete">删除</a-menu-item>
                    </a-menu>
                    <a-button>
                        更多操作
                        <a-icon type="down"/>
                    </a-button>
                </a-dropdown>
            </a-space>
            <standard-table
                    :columns="columns"
                    :dataSource="dataSource"
                    :selectedRows.sync="selectedRows"
                    rowKey="id"
                    @clear="onClear"
                    @change="onChange(arguments)"
                    @selectedRowChange="onSelectChange"
            >
                <div slot="status" slot-scope="{text}">
                    <a-tag :color="text ? 'green' : 'grey'">
                        {{text ? '正常' : '禁用'}}
                    </a-tag>
                </div>
                <div slot="action" slot-scope="{text, record}">
                    <a style="margin-right: 8px" @click="editUser(record)">
                        <a-icon type="edit"/>
                        编辑
                    </a>
                    <a-popconfirm
                            title="确定删除?"
                            ok-text="是"
                            cancel-text="否"
                            @confirm="confirmDelete(record.id)"

                    >
                        <a>
                            <a-icon type="delete"/>
                            删除
                        </a>
                    </a-popconfirm>
                </div>
                <template slot="statusTitle">
                    <a-icon @click.native="onStatusTitleClick" type="info-circle"/>
                </template>
            </standard-table>
        </div>
        <a-modal
                :title="action==='edit' ? '编辑用户' : '新增用户'"
                :visible="visible"
                :footer="null"
                :confirm-loading="confirmLoading"
                @cancel="handleCancel"
        >
            <a-form @submit="submit" :form="form">
                <a-form-item
                        :label="$t('id')"
                        :labelCol="{span: 7}"
                        :wrapperCol="{span: 10}"
                        v-if="action==='edit'"
                >
                    <a-input disabled   v-decorator="['id',{}]"/>
                </a-form-item>
                <a-form-item
                        :label="$t('account')"
                        :labelCol="{span: 7}"
                        :wrapperCol="{span: 10}"
                >
                    <a-input :placeholder="$t('accountInput')"  v-decorator="['account', {rules: [{ required: true, message: $t('accountInput'), whitespace: true}]}]" allow-clear autocomplete='username'/>
                </a-form-item>
                <a-form-item
                        :label="$t('pwd')"
                        :labelCol="{span: 7}"
                        :wrapperCol="{span: 10}"
                >
                    <a-input-password :placeholder="$t('pwdInput')"  v-decorator="['pwd',{rules: [ {validator: validate}]}]" allow-clear autocomplete='password'/>
                </a-form-item>
                <a-form-item
                        :label="$t('confirmPwd')"
                        :labelCol="{span: 7}"
                        :wrapperCol="{span: 10}"
                >
                    <a-input-password :placeholder="$t('confirmPwdInput')"
                                      v-decorator="['confirmPwd', {rules: [ {validator: pwdValidate}]}]"
                                      allow-clear autocomplete='new-password'/>
                </a-form-item>
                <a-form-item
                        :label="$t('email')"
                        :labelCol="{span: 7}"
                        :wrapperCol="{span: 10}"
                >
                    <a-input :placeholder="$t('emailInput')" v-decorator="['email', {}]"  allow-clear/>
                </a-form-item>
                <a-form-item
                        :label="$t('phone')"
                        :labelCol="{span: 7}"
                        :wrapperCol="{span: 10}"
                >
                    <a-input :placeholder="$t('phoneInput')" v-decorator="['phone', {}]"  allow-clear/>
                </a-form-item>
                <a-form-item
                        :label="$t('role')"
                        :labelCol="{span: 7}"
                        :wrapperCol="{span: 10}"
                >
                    <a-checkbox-group v-decorator="['role', {}]">
                        <a-row>
                            <a-col
                                    v-for="item in role"
                                    :key="item.id"
                                    :span="14"
                                    style="margin: 5px 0;"
                            >
                                <a-checkbox :value="item.id" checked>{{ item.roleName }}</a-checkbox>
                            </a-col>
                        </a-row>
                    </a-checkbox-group>
                </a-form-item>
                <a-form-item
                        :label="$t('status')"
                        :labelCol="{span: 7}"
                        :wrapperCol="{span: 10}"
                >
                    <a-radio-group v-decorator="['status', {}]">
                        <a-radio :value="item.value"
                                 :checked="item.checked"
                                 v-for="item in options"
                                 :key="item.value">
                            {{item.name}}
                        </a-radio>
                    </a-radio-group>
                </a-form-item>
                <a-form-item style="margin-left: 30px;margin-top: 24px" :wrapperCol="{span: 10, offset: 7}">
                    <a-button type="primary" htmlType="submit">{{$t('submit')}}</a-button>
                    <a-button style="margin-left: 8px" @click="handleCancel">{{$t('cancel')}}</a-button>
                </a-form-item>
            </a-form>
        </a-modal>
    </a-card>
</template>

<script>
    import StandardTable from '@/components/table/StandardTable'
    import {getUserList, updateUser, saveUser, deleteUser} from '@/services/user'
    import {roleSelect} from '@/services/role'
    const columns = [
        {
            title: 'id',
            dataIndex: 'id',
        },
        {
            title: '用户名',
            dataIndex: 'account',
        },
        {
            title: '电子邮箱',
            dataIndex: 'email',
            sorter: true,
        },
        {
            title: '手机号码',
            dataIndex: 'phone',
            sorter: true,
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            sorter: true
        },
        {
            title: '状态',
            dataIndex: 'status',
            scopedSlots: {customRender: 'status'}
        },
        {
            title: '操作',
            scopedSlots: {customRender: 'action'}
        }
    ];

    export default {
        name: 'userList',
        i18n: require('./i18n'),
        components: {StandardTable},
        data() {
            return {
                form: this.$form.createForm(this),
                visible: false,
                confirmLoading: false,
                advanced: false,
                action: '',
                columns: columns,
                dataSource: [],
                role: [],
                ownRole: [],
                selectedRows: [],
                options: [
                    {checked: true, value: 1, name: '启用'},
                    {checked: false, value: 0, name: '禁用'},
                ]
            }
        },

        created() {
            //获取用户列表
            this.getUserList();
        },
        methods: {
            validate(rule, value, f){
                if (value === undefined) {
                    f('密码不能为空！')
                }
                f()
            },
            pwdValidate (rule, value, f) {
                //新增
                if (this.action === 'add') {
                    if (value === undefined) {
                        f('密码不能为空！')
                    }
                    if (value !== this.form.getFieldValue('pwd')) {
                        f('密码不一致！')
                    }
                }else {
                    //修改
                    if (value !== undefined) {
                        //如果填写密码，调用规则
                        if (value !== this.form.getFieldValue('pwd')) {
                            f('密码不一致！')
                        }
                    }
                }
                f()
            },
            getUserList() {
                getUserList(this.page, this.limit).then(result => {
                    const res = result.data;
                    if (res && res.code === "00000") {
                        this.dataSource = res.result.list
                    } else {
                        this.$message.error(res.message, 3)
                    }
                })
            },
            submit(e) {
                e.preventDefault();
                this.form.validateFields((err) => {
                    if (!err) {
                        const id = this.form.getFieldValue('id');
                        const account = this.form.getFieldValue('account');
                        const confirmPwd = this.form.getFieldValue('confirmPwd');
                        const email = this.form.getFieldValue('email');
                        const phone = this.form.getFieldValue('phone');
                        const roleIdList = this.form.getFieldValue('role');
                        const status = this.form.getFieldValue('status');
                        if (this.action === 'add') {
                            saveUser(account, confirmPwd,email,phone,status,roleIdList).then(result => {
                                const res = result.data;
                                if (res && res.code === "00000") {
                                    this.$message.success(res.message, 1)
                                } else {
                                    this.$message.error(res.message, 1)
                                }
                            })
                        } else {
                            updateUser(id, account, confirmPwd,email,phone,status,roleIdList ).then(result => {
                                const res = result.data;
                                if (res && res.code === "00000") {
                                    this.$message.success(res.message, 1)
                                } else {
                                    this.$message.error(res.message, 1)
                                }
                            })
                        }
                        //刷新列表
                        this.getUserList();
                    }
                });
                this.visible = false;
            },
            handleCancel() {
                this.visible = false;
            },
            /** 确认删除**/
            confirmDelete(id){
                const ids = [];
                ids.push(id);
               this.deleteUser(ids)
            },
            /** 删除用户**/
            deleteUser(ids){
                deleteUser(ids).then(result => {
                    const res = result.data;
                    if (res && res.code === "00000") {
                        this.$message.success("操作成功", 1)
                        this.getUserList();
                    } else {
                        console.log(res.message);
                        this.$message.error(res.message, 1)
                    }
                });
            },
            /** 添加用户**/
            addUser() {
                //清空表单
                this.form.resetFields();
                //新增行为
                this.action = 'add';
                this.visible = true;
                //选中角色
                roleSelect().then(result => {
                    const res = result.data;
                    if (res && res.code === "00000") {
                        this.role = res.result.roleList;
                    } else {
                        this.$message.error(res.message, 1)
                    }
                });
            },
            /** 编辑用户**/
            editUser(row) {
                //清空表单
                this.form.resetFields();
                //编辑行为
                if (row) {
                    this.action = 'edit';
                }
                let ownRole=[];
                //打开会话框
                this.visible = true;
                //获取角色列表
                roleSelect().then(result => {
                    const res = result.data;
                    if (res && res.code === "00000") {
                        this.role = res.result.roleList;
                        ownRole = res.result.ownRoleIdList;
                        //数据回显
                        this.$nextTick(() => {
                            this.form.setFieldsValue({ // form表单赋值
                                id: row.id,
                                account: row.account,
                                pwd: null,
                                confirmPwd: null,
                                email: row.email,
                                status: row.status ,
                                phone: row.phone,
                                role: ownRole,
                            });
                        });
                    } else {
                        this.$message.error(res.message, 1)
                    }
                });
            },
            toggleAdvanced() {
                this.advanced = !this.advanced
            },
            onClear() {
                this.$message.info('您清空了勾选的所有行')
            },
            onStatusTitleClick() {
                this.$message.info('你点击了状态栏表头')
            },
            onChange(e) {
                console.log(e);
                this.$message.info('表格状态改变了')
            },
            onSelectChange() {
                this.$message.info('选中行改变了')
            },
            handleMenuClick(e) {
                if (e.key === 'delete') {
                    //删除
                    let self = this;
                    this.$confirm({
                        title: '确认提示',
                        content: `是否确认删除？`,
                        okButtonProps: {
                            color: this.themeColor,
                        },
                        onOk () {
                            self.selectedRows = self.selectedRows.map((item) => item.id);
                            self.deleteUser(self.selectedRows);
                        }
                    });
                }
            }
        }
    }
</script>

<style lang="less" scoped>
    .search {
        margin-bottom: 54px;
    }

    .fold {
        width: calc(100% - 216px);
        display: inline-block
    }

    .operator {
        margin-bottom: 18px;
    }

    @media screen and (max-width: 900px) {
        .fold {
            width: 100%;
        }
    }
</style>
